package cn.picclife.mwx.manager.sys.service.impl;

import java.math.BigDecimal;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.picclife.mwx.manager.sys.mapper.DataCollectMapper;
import cn.picclife.mwx.manager.sys.mapper.DataQualityCheckMapper;
import cn.picclife.mwx.manager.sys.model.bo.CheckQualityRequest;
import cn.picclife.mwx.manager.sys.model.bo.CheckQualityRes;
import cn.picclife.mwx.manager.sys.model.bo.PageCount;
import cn.picclife.mwx.manager.sys.model.bo.UserSessionBo;
import cn.picclife.mwx.manager.sys.model.po.Branch;
import cn.picclife.mwx.manager.sys.model.po.DataCollect;
import cn.picclife.mwx.manager.sys.model.po.DataQualityCheck;
import cn.picclife.mwx.manager.sys.service.CheckQualityService;

@Service
public class CheckQualityServiceImpl implements CheckQualityService{

	@Autowired
	private DataQualityCheckMapper dataQualityCheckMapper;
	
	@Autowired
	private DataCollectMapper dataCollectMapper;
	
	/**
	 * 获取抽检列表
	 * @param req
	 * @param request
	 * @throws Exception 
	 */
	public PageCount getDistributeCount(CheckQualityRequest req) throws Exception {
		
		PageCount pageCount = new PageCount();
		pageCount.setNowPage(req.getNowPage());//当前页
		pageCount.setRowNum(req.getRowNum());//每页多少条
		//查询总条数
		Map<String,Object> datemap = new HashMap<String,Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		datemap.put("startTime",null);
		datemap.put("endTime",null);
		datemap.put("organCode","");
		if(null!=req.getStartTime()&& req.getStartTime().trim().length()>0 && null!=req.getEndTime()
				&&req.getEndTime().trim().length()>0) {
			datemap.put("startTime",sdf.parse(req.getStartTime()));
			datemap.put("endTime",sdf.parse(req.getEndTime()));
		}
		if(null!=req.getOrganCode()&&!"".equals(req.getOrganCode())) {
			datemap.put("organCode", req.getOrganCode());
		}
		//总数
		int allCount = dataQualityCheckMapper.queryDataAllCount(datemap);
		if(0==pageCount.getRowNum()) {
			pageCount.setRowNum(10);
		}
		if(0==pageCount.getNowPage()) {
			pageCount.setNowPage(1);
		}
		int allPages = allCount / pageCount.getRowNum();

		if (allCount % pageCount.getRowNum() > 0) {
			allPages += 1;//总页数
		}

		pageCount.setAllPages(allPages);
		pageCount.setAllCount(allCount);
		int minTotal = (pageCount.getNowPage() - 1) * pageCount.getRowNum();
		int maxTotal = pageCount.getNowPage() * pageCount.getRowNum();
		pageCount.setMinTotal(minTotal);
		pageCount.setMaxTotal(maxTotal);
		pageCount.setMaxminTotal(maxTotal-minTotal);
		pageCount.setObject(datemap);
		datemap.put("minTotal", minTotal);
		datemap.put("maxminTotal", maxTotal-minTotal);
		List<DataQualityCheck> list = dataQualityCheckMapper.queryPageList(datemap);
				
		pageCount.setDatas(list);
		return pageCount;
	}
	
	/**
	 * 获取质检信息
	 * @throws Exception 
	 */
	public int getDistributeData(CheckQualityRequest req) throws Exception {
		
		//获取百分比
		BigDecimal percent =  new BigDecimal(req.getPercent()).divide(new BigDecimal("100")).setScale(3,BigDecimal.ROUND_HALF_UP);
		if(percent.floatValue()>1) {
			return 2;//质检比例不能超过1
		}
		
		Map<String,Object> datemap = new HashMap<String,Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startTime = null;
		Date endTime = null;
		if(null!=req.getStartTime()&&req.getStartTime().trim().length()>0) {
			String start = req.getStartTime()+" 00:00:00";
			startTime = sdf.parse(start);
		}
		if(null!=req.getEndTime()&&req.getEndTime().trim().length()>0) {
			String end = req.getEndTime()+" 23:59:59";
			endTime = sdf.parse(end);
		}
		datemap.put("startTime",startTime);
		datemap.put("endTime",endTime);
		datemap.put("organCode", req.getOrganCode());
		//如果百分数为100，则该条件下的百分比为1，则全部抽检
		if("100".equals(req.getPercent())) {
			int count = dataCollectMapper.queryDataAllCount(datemap);
			dataCollectMapper.updateDataAllCount(datemap);
			req.setCheckDataNo(count);
			return saveDistributeData(req);
		}
		//获取质检总数
		int count = dataCollectMapper.queryDataAllCount(datemap);//总数1153
		if(count==0) {
			return 3;//质检总数为0
		}
		//质检的数据量
		int getCount = new BigDecimal(count).multiply(percent).setScale(0,BigDecimal.ROUND_HALF_UP).intValue();//115
		
		List<DataCollect> list = dataCollectMapper.queryDataList(datemap);//具体总的集合信息
		//Random random = new Random();
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		StringBuffer str = new StringBuffer();
		List<String> dataCollectIdList = new ArrayList<String>();
		//获取随机数据
		//修改与20201223==============================================================================
		/*for(int i=0;i<getCount;i++) {//49
			boolean flag = true; 
			while(flag) {
				StringBuffer sb = new StringBuffer();
				//int ranNum = random.nextInt(getCount);
				int ranNum = random.nextInt(list.size());//在查得的数据中去随机获取getCount条1153
				sb.append(ranNum);
				if(str.toString().indexOf(sb.toString())<0) {
					DataCollect dataCollect = list.get(ranNum);
					dataCollectIdList.add(dataCollect.getId());
					str.append(ranNum);
					if (i<getCount-1) {
						str.append(","); //比如十条22,14,21,11,16,15,18,7,20,19防止类似注入
					}
					flag=false;
				}
			}
		}*/
		//修改与20201223==============================================================================
		int[] ints = randomCommon(0, list.size(), getCount);
		for (int i = 0; i <getCount ; i++) {
			int ranNum=ints[i];
			DataCollect dataCollect = list.get(ranNum);
			dataCollectIdList.add(dataCollect.getId());
			str.append(ranNum);
			if (i<getCount-1) {
				str.append(","); //比如十条22,14,21,11,16,15,18,7,20,19防止类似注入
			}
		}

		//更新随机数为审核中状态
		int result = dataCollectMapper.updateRandomList(dataCollectIdList);//updateDataAllCount
		if(result==0) {
			return 0;
		}
		req.setCheckDataNo(getCount);
		//将质检比例信息存入表
		return saveDistributeData(req);
	}

	public static int[] randomCommon(int min, int max, int n){
		if (n > (max - min + 1) || max < min) {
			return null;
		}
		int[] result = new int[n];
		for (int i = 0; i <result.length ; i++) {
			result[i]=-1;
		}
		int count = 0;
		while(count < n) {
			int num = (int) (Math.random() * (max - min)) + min;
			boolean flag = true;
			for (int j = 0; j < n; j++) {
				if(num == result[j]){
					flag = false;
					break;
				}
			}
			if(flag){
				result[count] = num;
				count++;
			}
		}
		return result;
	}
	
	/**
	 * 保存质检比例信息
	 * @param req
	 * @param request
	 * @throws Exception 
	 */
	public int saveDistributeData(CheckQualityRequest req) throws Exception {
		//将分配比例信息存入表
		DataQualityCheck check = new DataQualityCheck();
		check.setOptNo(req.getUser());//操作员
		check.setPercent(req.getPercent());//抽检比例
		check.setCreateTime(new Date());//创建时间
		check.setOrganCode(req.getOrganCode());//机构
		if(null==req.getOrganCode()||"".equals(req.getOrganCode())) {
			check.setOrganCode("10");//机构总公司
		}
		Branch branch = dataQualityCheckMapper.queryBranchByBranchCode(check.getOrganCode());
		if(null!=branch) {
			check.setOrganName(branch.getBranchName());//机构名称
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startTime = null;
		Date endTime = null;
		if(null!=req.getStartTime()&&req.getStartTime().trim().length()>0) {
			String start = req.getStartTime()+" 00:00:00";
			startTime = sdf.parse(start);
		}
		if(null!=req.getEndTime()&&req.getEndTime().trim().length()>0) {
			String end = req.getEndTime()+" 23:59:59";
			endTime = sdf.parse(end);
		}
		check.setCheckStartDate(startTime);//抽检开始时间
		check.setCheckEndDate(endTime);//抽检结束时间
		check.setCheckDataNo(req.getCheckDataNo());//抽检条数
		return dataQualityCheckMapper.saveCheckData(check);
	}
	
	/**
	 * 获取机构列表
	 * @return
	 */
	public List<Branch> getBranchList() {
		List<Branch>a= dataQualityCheckMapper.getBranchList();
		return a ;
	}
}
